import axios from 'axios'
import { MessageBox, Message, Loading } from 'element-ui'
// const URLafter = '/api'
// const baseURL: string = 'http://192.168.0.113:9080'
// const baseURL = process.env.NODE_ENV == 'production' ? 'http://59.110.54.18:9080' : 'http://192.168.0.108:9080'
const baseURL: string = 'http://59.110.54.18:9080'
// const baseURL = ''
// create an axios instance
export const http = axios.create({
    // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    baseURL: baseURL,
    // withCredentials: true,
    headers: {
        'X-Requested-With': 'XMLHttpRequest'
    },
    timeout: 60000 // 设置超时时间
})
/**
 * 请求拦截器，
 */
http.interceptors.request.use(
    (config: any): void => {
        // 请求携带token
        const token = sessionStorage.getItem('token')
        if (token != '' && token != null) {
            config.headers['token'] = token
        }
        // config.data = qs.stringify(config.data)

        return config
    },
    (error: any) => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

/**
 * 返回拦截器，
 */
http.interceptors.response.use(
    (response: any) => {
        const res = response.data
        // console.log(response)
        if (res.code != 200) {
            if (res.message) {
                Message.error(res.message)
            } else {
                Message.error(res.msg)
            }
            // errorHandle(res.code, res.message)
            return Promise.reject(res)
        }
        return res
    },
    (error: any) => {
        //超时处理
        console.log(String(error))
        if (String(error).includes('timeout')) {
            Message.warning('请求超时!')
            return
        }
        if (String(error).includes('Network')) {
            Message.warning('网络错误!')
            return
        }
        // console.log('错误')
        // console.log(error) // for debug
        // console.log(error.response.data) // for debug
        // errorHandle(error.response.data.status, error.response.data.message)
        return Promise.reject(error.response)
    }
)

//错误处理
const errorHandle = (status: any, other: any) => {
    // 状态码判断
    /**
     * @param {Object} status
     * 状态码和后台约定，进行相应操作
     * 请求成功	200
     * 请求失败	400
     * 内部错误	500
     * 未授权	401
     * 不合法的参数	40035
     * 请求超时	408
     */
    switch (status) {
        case 400:
            // 401: 未登录状态，跳转登录页
            Message.error(other)
            break
        case 401:
            Message.error(other)
            break
        case 500:
            Message.error('内部服务器错误')
            break
        case 404:
            Message.error(other)
            break
        case 408:
            Message.error(other)
            break
        default:
            console.log(other)
    }
}
